<template>
  <a-modal
    :visible="visible"
    :width="1000"
    okText="提交"
    cancelText="取消"
    :title="title"
    :destroyOnClose="true"
    :maskClosable="false"
    :keyboard="false"
    @cancel="closeModal(false)">
    <a-form :label-col="{ span: 7 }"
      :wrapper-col="{ span: 12 }">
      <a-form-item>
        <template slot="label">
          <span class="ant-form-item-required">
            套系标题
          </span>
        </template>
        <a-input
          autocomplete="off"
          v-model="formData.title"
          :disabled="disabled"
          :maxLength="32"
          style="width:240px;"
          placeholder="请输入套系标题，限32个汉字以内"
        />
      </a-form-item>
      <a-form-item>
        <template slot="label">
          <span>
            套系副标题
          </span>
        </template>
        <a-input
          autocomplete="off"
          v-model="formData.subhead"
          :disabled="disabled"
          style="width:240px;"
          :maxLength="38"
          placeholder="请输入套系标题，限38个汉字以内"
        />
      </a-form-item>
      <a-form-item>
        <template slot="label">
          <span class="ant-form-item-required">
            套系分类
          </span>
        </template>
        <a-button type="primary" :disabled="disabled" @click="handleAddClassify">增加套系归类</a-button>
        <div v-for="(item,index) in addClassifyList" :key="index">
          <a-space v-if="!disabled">
            <a-cascader
              :options="classifyList"
              :disabled="disabled"
              :allowClear="true"
              style="width:240px;"
              v-model="item.treepath"
              placeholder="请选择套系分类"/>
              <a-icon 
                class="dynamic-delete-button"
                type="minus-circle-o"
                @click="handleRemoveClassify(index)"/>
          </a-space>
          <a-space v-else>
            <a-input
              v-model="item.seriesClassificationName"
              :disabled="disabled"
              style="width:240px;"
            />
          </a-space>
        </div>
      </a-form-item>
      <a-form-item>
        <template slot="label">
          <span class="ant-form-item-required">
            套系封面
          </span>
        </template>
        <a-space class="main_picture">
          <ImageUpload v-model="formData.cover" :disabled="disabled" uploadTextHtml="上传套系封面"></ImageUpload>
          <p style="fontSize:'10px'">注：建议尺寸 540*540像素，小于1M的图片</p>
        </a-space>
      </a-form-item>
      <a-form-item label="设计理念">
        <a-textarea 
          placeholder="2-300个汉字" 
          :style="{width: '400px', minHeight: '100px'}"
          v-model="formData.designPhilosophy"
          :maxLength="300" 
          :disabled="disabled"
          auto-size />
      </a-form-item>
      <a-form-item label="是否展示角标" required>
        <a-radio-group 
          :options="yesOrNoList" 
          :disabled="disabled"
          v-model="formData.enableShowMark">
        </a-radio-group>
        <div class="cornerMarkInfo" v-show="formData.enableShowMark == 1">
          <a-space direction="vertical">
            <div>
              <span>角标标题：</span>
              <a-input 
                :style="{width: '60%'}" 
                v-model="formData.markTitle" 
                :disabled="disabled"
                placeholder="最多4个汉字" 
                :maxLength="4" />
            </div>
            <div> 
              角标背景色：
              <a-radio-group 
                :options="colorOptions" 
                :disabled="disabled"
                v-model="formData.markBackgroundColor">
              </a-radio-group>
            </div>
          </a-space>
        </div>
      </a-form-item>
      <a-form-item label="排序" required>
        <a-input-number
          style="width: 100px"
          v-model="formData.sort"
          :disabled="disabled"
        />
        <span :style="{fontSize:'14px',marginLeft:'10px'}">注：数字越往大越靠后，相同序号按添加时间倒序排序</span>
      </a-form-item>
      <a-form-item label="是否展示" required>
        <a-radio-group 
          :options="yesOrNoList" 
          :disabled="disabled"
          v-model="formData.enableShow">
        </a-radio-group>
      </a-form-item>
      <a-form-item label="设为新品" required>
        <a-radio-group 
          :options="yesOrNoList" 
          :disabled="disabled"
          v-model="formData.enableNew">
        </a-radio-group>
      </a-form-item>
      <a-form-item label="展示平台" required>
        <a-checkbox 
          :indeterminate="indeterminate" 
          :checked="platformCheckAll" 
          :disabled="disabled"
          @change="onPlatformCheckAllChange">
          全选
        </a-checkbox>
        <a-checkbox-group 
          :options="platformList" 
          v-model="showPlatform" 
          :disabled="disabled"
          @change="onPlatformChange">
        </a-checkbox-group>
      </a-form-item>
      <a-form-item label="分享话术">
        <a-col>
          <tinymce-editor v-model="formData.shareWord" :disabled="disabled"></tinymce-editor>
        </a-col>
      </a-form-item>
      <a-form-item label="是否关联其他产品" required>
        <a-radio-group v-model="formData.enableRelevanceProduct" :disabled="disabled">
          <a-radio :value="1">
            是<a-button
              v-if="formData.enableRelevanceProduct == 1"
              @click="addProduct"
              type="link"
              :style="{ padding: '0 10px' }"
              >添加产品</a-button
            >
          </a-radio>
          <a-radio :value="0"> 否 </a-radio>
        </a-radio-group>
        <table
          class="form-table"
          style="width: 600px"
          v-if="products.length > 0"
        >
          <thead>
            <tr>
              <th class="productName">名称</th>
              <th class="productType">类型</th>
              <th class="operation">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(product, index) in products" :key="index">
              <td class="productName">
                {{ product.productName }}
              </td>
              <td class="productType">{{ product.productType | filterProType }}</td>
              <td class="operation">
                <a-button
                  type="link"
                  :disabled="disabled"
                  @click="operationGoods(index, product, 'delete')"
                  >删除</a-button
                >
                <a-button
                  type="link"
                  v-if="index != 0"
                  :disabled="disabled"
                  @click="operationGoods(index, product, 'up')"
                  >上移</a-button
                >
                <a-button
                  type="link"
                  v-if="index != (products.length - 1)"
                  :disabled="disabled"
                  @click="operationGoods(index, product, 'down')"
                  >下移</a-button
                >
              </td>
            </tr>
          </tbody>
        </table>
      </a-form-item>
      <a-form-item label="是否共同卖点" required>
        <a-radio-group :options="yesOrNoList" :disabled="disabled" v-model="formData.enableShareSell"></a-radio-group>
        <template>
          <a-button type="primary" :disabled="disabled" v-if="formData.enableShareSell == 1" @click="handleAddSellpoint">添加共用详情</a-button>
          <ul v-if="formData.enableShareSell == 1">
            <li v-for="(item,index) in addSellpointList" :key="index">
              <a-select v-model="item.value" :disabled="disabled" style="width:240px;" @change="handleChangeSellpoint(item,index)">
                <a-select-option v-for="(item,index) in sellpointList" :key="index" :value="item.pointType+'_'+item.id">{{item.typeName}} / {{item.pointName}}</a-select-option>
              </a-select>
              <a-icon class="dynamic-delete-button remove_ellpoint"
                type="minus-circle-o" @click="handleRemoveSellpoint(item,index)"/>
            </li>
          </ul>
        </template>
      </a-form-item> 
    </a-form>
    <template slot="footer">
      <a-space>
        <a-button key="back" @click="closeModal(false)">取消</a-button>
        <a-button type="primary" :disabled="disabled" :loading="saveLoading" @click="handleSubmit(1)">保存</a-button>
        <a-button type="primary" :disabled="disabled" v-if="shopType == 1" :loading="publishLoading" @click="handleSubmit(2)">保存并发布门店</a-button>
      </a-space>
    </template>
    <AddProduct :visible="isAddProduct" @getProductList="getProductList" @cancel="isAddProduct = false"></AddProduct>
  </a-modal>
</template>

<script>
import deepCopy from '@/utils/deepCopy'
import { yesOrNo, showPlatformList } from '@/utils/dictData'
import ImageUpload from '@/components/antBase/ImageUpload'
import AddProduct from './AddProduct'
export default {
  components: {
    ImageUpload,
    AddProduct
  },
  name: 'NewSerises',
  props: {
    record: {
      type: Object,
      default () {
        return {}
      }
    },
    visible: {
      type: Boolean,
      default: false
    },
    // 店铺类型总店还是分店
    shopType: {
      type: [String, Number],
      require: true
    },
    opration: {
      type: [String, Number],
      default: '1'
    }
  },
  data () {
    return {
      // 添加分类归类
      addClassifyList: [],
      // 套系分类
      classifyList: [],
      // 套系封面
      screenPicture: '',
      // 是否展示角标
      yesOrNoList: yesOrNo,
      // 角标背景色
      colorOptions: [
        {label: '红色', value: 1},
        {label: '蓝色', value: 2},
        {label: '灰色', value: 3},
        {label: '黑色', value: 4}
      ],
      // 展示平台
      platformList: showPlatformList,
      sellpointList: [],
      addSellpointList: [],//添加的卖点
      indeterminate: false, //展示平台全选样式
      platformCheckAll: false,
      saveLoading: false,
      publishLoading: false,
      sellPointIds: '', //产品卖点id(多个用逗号隔开)
      products: [], //关联产品
      isAddProduct: false, //选择产品弹窗
      // 提交表单数据
      showPlatform: [], //展示平台
      formData: {
        title: '', //套系标题
        subhead: '', //套系副标题
        cover: '', //套系封面
        designPhilosophy: '', //设计理念
        enableShowMark: '', //是否展示角标
        markTitle: '', //角标标题
        markBackgroundColor: '', //角标背景色
        sort: '', //排序
        enableShow:'', //是否展示
        enableNew: '', //是否设为新品
        shareWord: '', //分享话术
        enableRelevanceProduct: '', //1是 0否 是否关联其他产品
        enableShareSell: '', //是否共用卖点
      }
    }
  },
  watch: {
    visible (newVal) {
      this.resetData();
      this.saveLoading = false;
      this.publishLoading = false;
      if(newVal === true) {
        this.getClassifyList();
        this.getSellpointList();
        if(this.opration != 1) {
          this.getSerisesDetail();
        }
      }
    },
    'formData.enableShowMark'(newVal) {
      if(newVal != 1) {
        this.formData.markTitle = '';
        this.formData.markBackgroundColor = '';
      }
    },
    'formData.enableShareSell'(newVal) {
      if(newVal != 1) {
        this.addSellpointList = [];
      }
    },
    'formData.enableRelevanceProduct'(newVal) {
      if(newVal != 1) {
        this.products = [];
      }
    }
  },
  computed: {
    title() {
      switch(+this.opration) {
        case 1:
          return '新增套系';
        case 2:
          return '编辑套系'
        case 3:
          return '查看套系'
      }
    },
    productList() {
      if(this.products.length == 0) return [];
      return this.products.map((item, index) => {
        return {
          productId: item.productId || null,
          productType: item.productType,
          sort: index,
          id: item.id || null
        }
      })
    },
    disabled() { //查看
      return this.opration == '3';
    }
  },
  filters: {
    filterProType(type) {
      switch(+type) {
        case 1:
          return '图库'
        case 2:
          return '案例'
        case 3:
          return '视频'
        case 4:
          return '实拍图'
      }
    }
  },
  methods: {
    // 数据重置
    resetData () {
      this.formData = {
        title: '', //套系标题
        subhead: '', //套系副标题
        cover: '', //套系封面
        designPhilosophy: '', //设计理念
        enableShowMark: '', //是否展示角标
        markTitle: '', //角标标题
        markBackgroundColor: '', //角标背景色
        sort: '', //排序
        enableShow:'', //是否展示
        enableNew: '', //是否设为新品
        shareWord: '', //分享话术
        enableRelevanceProduct: '', //1是 0否 是否关联其他产品
        enableShareSell: '', //是否共用卖点
      }
      this.showPlatform = [];
      this.addClassifyList = [];
      this.products = [];
    },
    operationGoods(index, product, type) {
      switch(type) {
        case 'delete':
          this.products.splice(index, 1)
        break;
        case 'up':
          let preItem = this.products[index - 1];
          let currentIndex = index - 1;
          console.log(preItem, currentIndex)
          this.$set(this.products, index, preItem);
          this.$set(this.products, currentIndex, product);
        break;
        case 'down':
          let nextItem = this.products[index + 1];
          let activeIndex = index + 1;
          console.log(nextItem, activeIndex)
          this.$set(this.products, index, nextItem);
          this.$set(this.products, activeIndex, product);
        break;
      }
    },
    // 如果是编辑 或者 查看 ，去查询套系详情并回显到页面
    async getSerisesDetail () {
      let id = this.record.id
      if (!id) return;
      let res = await this.$get('/gallery/series/id', { id })
      if (res && res.returnCode == 1000) {
        let tmpObj = res.dataInfo;
        // 套系分类
        if (tmpObj.seriesClassificationList?.length > 0) {
          this.addClassifyList = [];
          tmpObj.seriesClassificationList.forEach(item => {
            this.addClassifyList.push({
              id: item.id,
              treepath: item.treepath.split(',') || [item.treepath],
              seriesClassificationName: this.opration == 3 ? item.seriesClassificationName : undefined
            })
          })
        }
        // 获取产品列表
        this.products = tmpObj.products?.length > 0 ? tmpObj.products.map(item => {
          return {
            id: item.id || null,
            productId: item.productId,
            productType: item.productType,
            productName: item.productName,
            sort: item.sort
          }
        }).sort((a, b) => a.sort - b.sort) : [];
        for(let key in this.formData) {
          this.formData[key] = tmpObj[key];
        }
        // 展示平台
        this.showPlatform = tmpObj.exhibitionPlatform && tmpObj.exhibitionPlatform.split(',').map(item => {
          return parseInt(item);
        })
        this.formatSellPoint(tmpObj.sellPointIds);
      }
    },
    //卖点回显结果处理，格式：卖点类型_卖点名称
    formatSellPoint(sellPointIdsStr = ''){
      console.log(sellPointIdsStr)
      if(sellPointIdsStr) {
        let sellPointIds = sellPointIdsStr.includes(',') ? sellPointIdsStr.split(',') : [sellPointIdsStr]; 
        sellPointIds.forEach(item => {
          let pointType = '';
          this.sellpointList.forEach(item2 => {
            if(item == item2.id){
              pointType = item2.pointType;
            }
          })
          this.addSellpointList.push({
            value: pointType + '_' + item
          });
        })
      }
    },
    // 选择产品回调
    getProductList(list) {
      let arr = this.products.concat(list);
      let hash = {};
      this.products = arr.reduce((item, next) => {
        hash[next.productId] ? '' : (hash[next.productId] = true && item.push(next));
        return item
      }, [])
      this.isAddProduct = false;
    },
    // 重置分类格式
    formatClassifyList (data) {
      let tmpData = []
      for (let i = 0; i < data.length; i++) {
        let item = {
          label: data[i].classificationName,
          value: data[i].id
        }
        if (data[i].children && data[i].children.length > 0) {
          item['children'] = this.formatClassifyList(data[i].children)
        }
        tmpData.push(item)
      }
      console.log('tmpData', tmpData)
      return tmpData
    },
    // 产品分类
    async getClassifyList () {
      let res = await this.$get('/gallery/classification/list')
      console.log(res)
      if (res && res.returnCode == 1000 && res.dataInfo) {
        let tmpData = this.formatClassifyList(res.dataInfo || [])
        this.classifyList = tmpData.filter(item => {
          return item.children && item.children.length > 0
        })
        console.log('this.classifyList', this.classifyList)
      }
    },
    // 添加产品
    addProduct() {
      this.isAddProduct = true;
    },
    // 展示平台 - 单选
    onPlatformChange(checkedList) {
      this.indeterminate = !!checkedList.length && checkedList.length < this.platformList.length;
      this.platformCheckAll = checkedList.length === this.platformList.length;
    },
    // 展示平台 - 全选
    onPlatformCheckAllChange(e) {
      this.showPlatform = e.target.checked ? this.platformList.map((item) => item.value) : [];
      this.indeterminate = false;
      this.platformCheckAll = e.target.checked;
    },
    //卖点列表查询
    async getSellpointList(){
      let res = await this.$get('/sellpoint/list');
      if(res && res.returnCode == '1000'){
        this.sellpointList = res.dataInfo || [];
        console.log(' this.sellpointList', this.sellpointList)
      }
    },
    //产品卖点  切换验证
    handleChangeSellpoint(currentItem, currentIndex, isAutoClear = true){
      let result = this.addSellpointList.find((item, index)=>{
        if(!item.value || !currentItem.value){
          return false;
        }
        return item.value.split('_')[0] === currentItem.value.split('_')[0] && currentIndex !== index;
      })
      if(result != undefined){
        if(isAutoClear){
          this.addSellpointList[currentIndex].value = '';
        }
        this.$message.error('一个详情类型只能选择一次')
        return 2;
      }
    },
    //产品卖点  移出
    handleRemoveSellpoint(item, index){
      this.addSellpointList.splice(index, 1);
    },
    getAllSellpointIds(){
      return this.addSellpointList.map(item => {
        return item.value.split('_')[1];
      }).filter(item => item);
    },
    //产品卖点  添加
    handleAddSellpoint(){
      if(this.addSellpointList.length >= 4){
        return this.$message.error('详情最多添加4个')
      }
      this.addSellpointList.push({
        value:'',
      });
    },
    // 添加分类归类
    handleAddClassify () {
      if (this.addClassifyList.length < 3) {
        this.addClassifyList.push({
          treepath: [],
          id: null
        })
      } else {
        this.$message.error('最多添加三个分类')
      }
    },
    // 移出分类归类
    handleRemoveClassify (index) {
      this.addClassifyList.splice(index, 1)
    },
    closeModal (freshTable) {
      this.resetData()
      this.$emit('cancel', freshTable)
    },
    // 提交
    async handleSubmit(type) {
      if (!this.formData.title) {
        this.$message.error('请输入套系标题')
        return
      }
      let addClassifyList = this.addClassifyList.map(item => {
        return {
          treepath: item.treepath.join(','),
          id: item.id
        }
      }).filter(item => {
        return item
      })
      if (!addClassifyList.length) {
        this.$message.error('请选择套系分类')
        return
      }
      if (addClassifyList.length > 3) {
        this.$message.error('最多添加三个套系分类')
        return
      }
      if (Array.from(new Set(addClassifyList)).length != addClassifyList.length) {
        this.$message.error('套系分类存在重复')
        return
      }
      if (!this.formData.cover) {
        this.$message.error('请上传套系封面')
        return
      }
      if (this.formData.enableShowMark === '') {
        this.$message.error('请选择是否展示角标')
        return
      }
      if (this.formData.enableShowMark) {
        if(this.formData.markTitle === '') {
          this.$message.error('请输入角标标题')
          return
        }
        if(this.formData.markBackgroundColor === '') {
          this.$message.error('请选择角标背景色')
          return
        }
      }
      if (this.formData.sort === '') {
        this.$message.error('请输入排序')
        return
      }
      if (this.formData.enableShow === '') {
        this.$message.error('请选择是否展示')
        return
      }
      if (this.formData.enableNew === '') {
        this.$message.error('请选择是否设为新品')
        return
      }
      if (this.showPlatform.length == 0) {
        this.$message.error('请选择展示平台')
        return
      }
      if(this.formData.enableRelevanceProduct === ''){
        this.$message.error('请选择是否关联其他产品')
        return
      }
      if(this.formData.enableRelevanceProduct == 1 && this.products.length == 0) {
        this.$message.error('请选择产品')
        return
      }
      if(!this.formData.enableShareSell === ''){
        this.$message.error('请选择是否共同卖点')
        return
      }
      let sellPointIds;
      if(this.formData.enableShareSell == 1) {
        sellPointIds = this.getAllSellpointIds();
        if(sellPointIds.length == 0){
          this.$message.error('请选择产品卖点!')
          return;
        }
        for(let i = 0; i < this.addSellpointList.length; i++){
          let item = this.addSellpointList[i];
          if(this.handleChangeSellpoint(item, i, false) == 2){
            return;
          }
        }
      }
      type == 1 ? this.saveLoading = true : this.publishLoading = true;
      let postUrl = this.opration == 1 ? 'gallery/series/add' : 'gallery/series/update';
      const res = await this.$post(postUrl, {
        ...this.formData,
        id: this.opration == 2 ? this.record.id : undefined,
        seriesClassificationList: addClassifyList, // 图库分类id集合
        exhibitionPlatform: this.showPlatform.join(','),
        sellPointIds:this.formData.enableShareSell == 1 ? sellPointIds.join(',') : '',
        products: this.productList
      });
      this.saveLoading = false;
      this.publishLoading = false;
      if (res && res.returnCode === 1000) {
        this.$message.success('保存成功！');
        this.$emit('cancel', type == 1, type == 2 ? {
          seriesIds: res.dataInfo || this.record.id
        } : null)
      }
    }
  }
}
</script>

<style lang="less" scoped>
::-webkit-input-placeholder { /* WebKit browsers */
  color: #ccc;
  font-size: 14px;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}
input[type="number"]{
    -moz-appearance: textfield;
}
.avatar_img{
  max-width:104px;
}
.main_picture{
  /deep/ .ant-upload{
    width:104px!important;
    height:104px!important;
    .anticon {
      margin-top: 18px;
      svg{
        font-size:24px;
      }
    }
    img{
      //display: block;
      max-width: 100%;
      max-height: 100%;
    }
    .ant-upload-text{
      font-size:12px;
    }
  }
}
.form-table {
  tr {
    .productName {
      width: 300px;
    }
    .productType {
      width: 100px;
    }
    .operation {
      width: 200px;
    }
  }
}
</style>
